package com.g4m.baselib.interceptor.admin;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.g4m.baselib.component.PremissionException;
import com.g4m.baselib.interceptor.annotation.RequiredAdminPermission;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  haosenwei[haosenwei@hudesen.com]
 *  21/02/2021 11:08
 * <p>Copyright 2008-2019 snsndk.com</p>
 */
@Component
public class GlobalAdminRequestInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }


        HandlerMethod handlerMethod = (HandlerMethod) object;

        RequiredAdminPermission requiredAdminPermission = handlerMethod.getMethod().getAnnotation(RequiredAdminPermission.class);
        if (requiredAdminPermission == null) {
            requiredAdminPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredAdminPermission.class);
        }

        //没有注解或注解为需要验证的一律过权限检查
        if (requiredAdminPermission == null || requiredAdminPermission.required()) {
            // 从 http 请求头中取出 token
            String token = httpServletRequest.getHeader("token");
            // 执行认证
            if (token == null) {
                throw new PremissionException("无token，请重新登录");
            }
            // 获取 token 中的 user id
            Integer userId;
            try {
                userId = JWT.decode(token).getClaim("id").asInt();
                if (userId == null || userId <= 0) {
                    throw new PremissionException("请登陆");
                }
            } catch (JWTDecodeException j) {
                throw new PremissionException("请重新登陆");
            }
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
